<?php
class SVN_Updater_Filter_BugtraqLinks implements SVN_Updater_Filter
{
	public function __construct($regexp, $bugtraqUrl) 
	{
		$this->_url = $bugtraqUrl;
		$this->_setRegexp($regexp);
	}

	private function _setRegexp($regexp) 
	{
		//   \/e -> \/e
		//   \\/e -> \\\/e
		$this->_regexp = '/';
		$escaped = false;
		foreach (str_split($regexp) as $char) {
			switch ($char) {
				case '\\':
					$escaped = !$escaped;
				break;
				case '/':
					if (!$escaped) {
						$this->_regexp .= '\\';
					}
					$escaped = false;
				break;
				default:
					$escaped = false;
			}
			$this->_regexp .= $char;
		}
		$this->_regexp .= '/';
	}
	
	public function filter($text) 
	{
		preg_match_all($this->_regexp, $text, $matches, PREG_PATTERN_ORDER);		
		$urls = array();
		unset($matches[0]);
		foreach ($matches as $matchSet) {
			foreach ($matchSet as $match) {
				$urls[] = str_replace('%BUGID%', $match, $this->_url);
			}
		}
		if (count($urls)) {
			$text .= "\n\nLinked bugs:\n" . join("\n", $urls); 
		}
		return $text;
	}
}
